package com.huahua.graduateschoolspringboot.handler;

import cn.hutool.core.text.StrFormatter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import com.huahua.graduateschoolspringboot.entity.dto.light.LightHeartDTO;
import com.huahua.graduateschoolspringboot.entity.po.CityLightDevice;
import com.huahua.graduateschoolspringboot.enums.DeviceTypeEnum;
import com.huahua.graduateschoolspringboot.service.CityLightDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LoveHuaHua
 * @date 2023年05月07日 10:44
 * @description believe in yourself
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class LightDeviceCommandHandler implements IDeviceCommandHandler {

    private final ObjectMapper objectMapper;
    private final CityLightDeviceService cityLightDeviceService;

    /**
     * 是否支持
     *
     * @param deviceType 设备类型
     * @return boolean
     */
    @Override
    public boolean support(String deviceType) {
        return DeviceTypeEnum.LIGHT.getPackageIdentification().equals(deviceType);
    }

    /**
     * 执行
     *
     * @param objectNode 对象节点
     */
    @Override
    public void execute(ObjectNode objectNode) throws JsonProcessingException {
        LightHeartDTO lightHeartDTO = objectMapper.readValue(objectMapper.writeValueAsString(objectNode), LightHeartDTO.class);
        LightHeartDTO.LampStatusDTO lampStatus = lightHeartDTO.getLampStatus();
        //光亮
        int brightness = lampStatus.getBrightness();
        //每一个灯的状态
        List<Integer> statusList = lampStatus.getStatus();
        ArrayList<CityLightDevice> entityList = Lists.newArrayList();
        //从 1 - n+1循环 因为数据id从1开始
        for (int i = 1; i <= statusList.size(); i++) {
            //因为i+1了 所以这里需要通过-1重新取出来
            Integer status = statusList.get(i - 1);
            CityLightDevice e = new CityLightDevice();
            e.setId(i);
            e.setDeviceName(StrFormatter.format("路灯{}号", i));
            e.setBrightness(brightness);
            if (brightness <= 0){
                e.setStatus(0);
            }else{
                e.setStatus(status);
            }
            entityList.add(e);
        }
        //更新每一个灯的状态
        cityLightDeviceService.saveOrUpdateBatch(entityList);

    }
}
